<script setup lang="ts">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import Plus from "~icons/ep/plus";
import "plus-pro-components/es/components/dialog-form/style/css";
import "jsoneditor/dist/jsoneditor.min.css";
import { setBanner, addBanner } from "@/api/common";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import { fixImageUrl, handleImagesUpload } from "@/utils/common";
defineOptions({
  name: "OperateBanner"
});
import {
  PlusSearch,
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";
import { useMenu } from "@/utils/power";
const power = useMenu(["add", "edit"]);

const edit = ref(false);

const imageFile = (path: any) => {
  return path.split(",").map((path: any) => {
    return { url: fixImageUrl(path), name: path.split("/").pop() };
  });
};

const rules = {
  title: [
    {
      required: true,
      message: "标题必填"
    }
  ]
};
// linkType 12 url可选 "云盒": 1,"水机": 3,"充电宝": 4

const formColumns: PlusColumn[] = [
  {
    label: "产品图片",
    prop: "image"
  },
  {
    label: "链接类型",
    prop: "linkType",
    valueType: "select",
    options: [
      {
        label: "无跳转",
        value: 0
      },
      {
        label: "图片",
        value: 1
      },
      {
        label: "文章",
        value: 2
      },
      {
        label: "视频",
        value: 3
      },
      {
        label: "VR",
        value: 4
      },
      {
        label: "直播",
        value: 5
      },
      {
        label: "话题",
        value: 6
      },
      {
        label: "商品",
        value: 7
      },
      {
        label: "云盒",
        value: 8
      },
      {
        label: "算力",
        value: 9
      },
      {
        label: "水机",
        value: 10
      },
      {
        label: "充电宝",
        value: 11
      },
      {
        label: "金融列表",
        value: 12
      }
    ]
  },
  {
    label: "内容",
    prop: "url"
  },
  {
    label: "排序",
    prop: "weight",
    valueType: "input-number"
  },
  {
    label: "是否开启",
    prop: "status",
    valueType: "radio",
    options: [
      {
        label: "开启",
        value: 1
      },
      {
        label: "禁用",
        value: 2
      }
    ]
  }
];
const visible = ref(false);
const values = ref<FieldValues>({});
const {
  loading,
  columns,
  dataList,
  loadingConfig,
  adaptiveConfig,
  onKeywordChange,
  loadData
} = useColumns();
const columnsRef = computed(() => {
  if (power.value.edit) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});
const editClick = async row => {
  Object.assign(values.value, row);
  edit.value = true;
  visible.value = true;
};

const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  confirmLoading.value = true;
  console.log(updatedValues, "updatedValues");
  if (edit.value) {
    try {
      const params = {
        bId: updatedValues.bId,
        image: updatedValues.image,
        type: searchValues.value.type,
        link_type: updatedValues.linkType,
        status: updatedValues.status,
        weight: updatedValues.weight,
        url: updatedValues.url
      };
      await setBanner(params);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("修改成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      const params = {
        image: updatedValues.image,
        type: searchValues.value.type,
        link_type: updatedValues.linkType,
        status: updatedValues.status,
        weight: updatedValues.weight,
        url: updatedValues.url
      };
      await addBanner(params);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};

const addProduct = () => {
  console.log("%c点击了添加商品>>>: ", "color: MidnightBlue; font-size: 20px;");
  edit.value = false;
  values.value = { weight: 0, status: 1, linkType: 0 };
  visible.value = true;
};

const formRef = ref();
const productImageRef = ref<UploadInstance>();
const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  values.value.image = res.data;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.image = undefined;
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};

const defaultSearchState = ref({ type: 1 });
const searchValues = ref({ type: 1 });

const searchColumns: PlusColumn[] = [
  {
    label: "Banner类别",
    prop: "type",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "首页",
        value: 1
      },
      {
        label: "商城首页",
        value: 2
      }
    ]
  }
];

const handleSearch = (value: any, old: any) => {
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  onKeywordChange(value);
};
const handleReset = value => {
  onKeywordChange(value);
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>产品专区</h3>
        </template>
        <template v-if="power.add" #extra>
          <el-button type="primary" @click="addProduct">
            <el-icon :size="15" color="#fff">
              <IconifyIconOffline :icon="Plus" />
            </el-icon>
            添加Banner
          </el-button>
        </template>
        <PlusSearch
          v-model="searchValues"
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @change="handleChange"
          @search="handleSearch"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
    >
      <template #image="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="row.image"
          class="h-[100px]"
          fit="cover"
          :initial-index="index"
          :preview-src-list="dataList.map(item => item.image)"
        />
      </template>
      <template #operation="{ row }">
        <el-button
          v-if="power.edit"
          type="primary"
          size="small"
          @click="editClick(row)"
          >编辑</el-button
        >
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="编辑产品专区"
      @confirm="handleSubmit"
    >
      <template #plus-field-url>
        <el-radio-group v-if="values.linkType === 12" v-model="values.url">
          <el-radio-button label="云盒" value="1" />
          <el-radio-button label="算力" value="2" />
          <el-radio-button label="水机" value="3" />
          <el-radio-button label="充电宝" value="4" />
        </el-radio-group>
        <el-input v-else v-model="values.url" placeholder="请输入内容" />
      </template>
      <template #plus-field-image>
        <el-upload
          ref="productImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.image && values.image.length > 0
              ? imageFile(values.image)
              : []
          "
          :on-success="handleIconImageSuccess"
          :on-remove="handleIconImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleIconImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped>
::deep .wot-message-box__icon--warning {
  --el-messagebox-color: red;
  color: red !important;
  fill: red !important;
}
</style>
